package com.edu.atams.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.atams.common.lang.Result;
import com.edu.atams.entity.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author czj666
 * @since 2021-10-09
 */
@RestController
@RequestMapping("/parent")
public class ParentController extends BaseController {

    @GetMapping("/list")
    public Result list(String parentName){
        Page<Parent> page = parentService.page(getPage(), new QueryWrapper<Parent>()
                .like(StrUtil.isNotBlank(parentName), "name", parentName));

        page.getRecords().forEach(p -> {
            List<StudentParent> studentParents = studentParentService.list(new QueryWrapper<StudentParent>().eq("parent_id", p.getId()));
            List<Integer> studentId = studentParents.stream().map(studentParent -> studentParent.getStudentId()).collect(Collectors.toList());
            if (studentId.size() > 0){

                List<Student> students = studentService.listByIds(studentId);
                ArrayList<StudentList> studentLists = new ArrayList<>();
                for (Student student : students) {
                    StudentList studentList = new StudentList();
                    studentList.setSchoolno(student.getSchoolno());
                    studentLists.add(studentList);
                }
                for (StudentList studentList : studentLists) {
                    for (StudentParent studentParent : studentParents) {
                        studentList.setRelation(studentParent.getFamilyRelation());
                    }
                }
                p.setStudentList(studentLists);

            }else {
                ArrayList<StudentList> studentLists = new ArrayList<>();
                p.setStudentList(studentLists);
            }

        });
        return Result.succ(page);
    }

    @PostMapping("/save")
    @Transactional
    public Result save(@RequestBody Parent parent){
        List<String> schoolnoList = parent.getStudentList().stream().map(p -> p.getSchoolno()).collect(Collectors.toList());
        //判断学号是否重复
        long count = schoolnoList.stream().distinct().count();
        if (schoolnoList.size() != count){
            return Result.fail("学号重复了");
        }
        List<Student> students = studentService.list(new QueryWrapper<Student>().in("schoolNo", schoolnoList));
        //添加学生-家长表
        if (students.size() == parent.getStudentList().size()){
            parentService.save(parent);
            List<Integer> studentIds = students.stream().map(s -> s.getId()).collect(Collectors.toList());

            List<StudentParent> studentParents = new ArrayList<>();

            for (int i = 0;i < parent.getStudentList().size();i ++){
                StudentParent studentParent = new StudentParent();
                studentParent.setFamilyRelation(parent.getStudentList().get(i).getRelation());
                studentParent.setParentId(parent.getId());
                studentParent.setStudentId(studentIds.get(i));
                studentParents.add(studentParent);
            }

            studentParentService.saveBatch(studentParents);

            //添加账号
            SysUser sysUser = new SysUser();
            sysUser.setRoleType(3);
            sysUser.setUsername(parent.getTel());
            String password = bCryptPasswordEncoder.encode("123456");
            sysUser.setPassword(password);
            sysUserService.save(sysUser);

            return Result.succ("");
        }else {
            return Result.fail("孩子学号有误");
        }

    }

    @PostMapping("/update")
    @Transactional
    public Result update(@RequestBody Parent parent){
        List<String> schoolnoList = parent.getStudentList().stream().map(p -> p.getSchoolno()).collect(Collectors.toList());
        //判断学号是否重复
        long count = schoolnoList.stream().distinct().count();
        if (schoolnoList.size() != count){
            return Result.fail("学号重复了");
        }
        List<Student> students = studentService.list(new QueryWrapper<Student>().in("schoolNo", schoolnoList));
        //添加学生-家长表
        if (students.size() == parent.getStudentList().size()){
            Parent parentById = parentService.getById(parent.getId());
            String tel = parentById.getTel();
            //更新账号名
            SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", tel));

            sysUser.setUsername(parent.getTel());
            sysUserService.updateById(sysUser);

            parentService.updateById(parent);
            List<Integer> studentIds = students.stream().map(s -> s.getId()).collect(Collectors.toList());

            List<StudentParent> studentParents = new ArrayList<>();

            for (int i = 0;i < parent.getStudentList().size();i ++){
                StudentParent studentParent = new StudentParent();
                studentParent.setFamilyRelation(parent.getStudentList().get(i).getRelation());
                studentParent.setParentId(parent.getId());
                studentParent.setStudentId(studentIds.get(i));
                studentParents.add(studentParent);
            }

            studentParentService.remove(new QueryWrapper<StudentParent>().eq("parent_id",parent.getId()));
            studentParentService.saveBatch(studentParents);


            return Result.succ("");
        }else {
            return Result.fail("孩子学号有误");
        }

    }

    @PostMapping("/remove")
    @Transactional
    public Result remove(@RequestBody Integer[] ids){
        //删除账号
        List<Parent> parents = parentService.listByIds(Arrays.asList(ids));
        System.out.println(parents);
        List<String> tels = parents.stream().map(p -> p.getTel()).collect(Collectors.toList());
        List<SysUser> sysUsers = sysUserService.list(new QueryWrapper<SysUser>().in("username", tels));
        sysUserService.removeByIds(sysUsers.stream().map(s -> s.getId()).collect(Collectors.toList()));
        //删除student-parent的数据
        studentParentService.remove(new QueryWrapper<StudentParent>().in("parent_id",Arrays.asList(ids)));
        //删除parent表数据
        parentService.removeByIds(Arrays.asList(ids));
        return Result.succ("");

    }


}
